﻿using System;
using System.Collections.Generic;
using System.Collections.ObjectModel;
using System.Linq;
using System.Net;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Documents;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Animation;
using System.Windows.Shapes;
using CommunitySystem.Assert;
using CommunitySystem.Ctrls;
using CommunitySystem.EmpbasicService;
using CommunitySystem.Views;
using EHR.Common;

namespace CommunitySystem
{
    public partial class PeiXunEmpControl : AsyncCtrl, IReturnListenerc
    {
        #region IReturnListenerc 成员
        public void BeginReturn()
        {
            selected.IsChecked = true;
            string or = "";
            if (orgids.Count > 0)
            {
                foreach (string i in orgids)
                {
                    or += i + ",";
                }
                or = or.Substring(0, or.Length - 1);
            }
            else or = "0";
            LoadData(or);
        }
        #endregion
        public NavMoveSwitch Nav { get; set; }
        private EmpbasicService.EmpBasicServiceClient Client = new EmpbasicService.EmpBasicServiceClient();
        private PeiXunService.PeiXunServiceClient client1 = new PeiXunService.PeiXunServiceClient();
        public ObservableCollection<EmpbasicService.OrgForHRModel> OrgList =
            new ObservableCollection<EmpbasicService.OrgForHRModel>();
        ObservableCollection<EmpbasicService.OrgForHRModel> forumList = new ObservableCollection<EmpbasicService.OrgForHRModel>();
        public PeiXunEmpControl()
        {
            InitializeComponent();
            selected.IsChecked = true;
            CheckBox_Click(selected, null);
            ListBoxOfLife.Items.Clear();
            Client.GetDengLuJueSeCompleted += new EventHandler<EmpbasicService.GetDengLuJueSeCompletedEventArgs>(Client_GetDengLuJueSeCompleted);
            Client.GetDengLuJueSeAsync(Session.LoginUser.LoginName);
            Client.GetOrgForHRModelCompleted += new EventHandler<EmpbasicService.GetOrgForHRModelCompletedEventArgs>(Client_GetOrgForHRModelCompleted);
            Client.GetOrgForHRModelbyIDsCompleted += new EventHandler<EmpbasicService.GetOrgForHRModelbyIDsCompletedEventArgs>(Client_GetOrgForHRModelbyIDsCompleted);
            Client.GetDengLuOrgCompleted += new EventHandler<GetDengLuOrgCompletedEventArgs>(Client_GetDengLuOrgCompleted);
            client1.PeiXunEmpCompleted += new EventHandler<PeiXunService.PeiXunEmpCompletedEventArgs>(client1_PeiXunEmpCompleted);
            client1.GetPeiXunModelCompleted += new EventHandler<PeiXunService.GetPeiXunModelCompletedEventArgs>(client1_GetPeiXunModelCompleted);
            client1.ShiFouChaoGuoPiaoShuCompleted += new EventHandler<PeiXunService.ShiFouChaoGuoPiaoShuCompletedEventArgs>(client1_ShiFouChaoGuoPiaoShuCompleted);
        }

        

        private void CheckBox_Click(object sender, System.Windows.RoutedEventArgs e)
        {
            // 在此处添加事件处理程序实现。
            RadioButton rb = sender as RadioButton;
            if (rb != null)
            {
                switch (rb.Name)
                {
                    case "selected":
                        DGRole_admin.Visibility = System.Windows.Visibility.Collapsed;
                        NewData_admin.Visibility = System.Windows.Visibility.Visible;
                        DGRole.Visibility = System.Windows.Visibility.Visible;
                        break;
                    case "unselected":
                        //DGRole_admin.Visibility = System.Windows.Visibility.Visible;
                        //NewData_admin.Visibility = System.Windows.Visibility.Collapsed;
                        //DGRole.Visibility = System.Windows.Visibility.Collapsed;
                        var seljw = this.DGRole.SelectedItem as PeiXunService.PeiXunModel;
                        if (seljw != null)
                        {
                            PeiXunEmpWindow view = new PeiXunEmpWindow(seljw.ID, orgids.Count > 0 ? Convert.ToInt32(orgids[0]):0);
                            //view.Nav = this.Nav;
                            Nav.ShowNextPage("订票人员情况", view, this);
                        }
                        else
                        {
                            SilverlightMessageBoxLibrary.Message.ErrorMessage("请先选择一条培训用于查看订票情况！");
                            selected.IsChecked = true;
                        }
                        break;
                }
            }
        }

        #region 获得组织机构树
        void Client_GetOrgForHRModelCompleted(object sender, EmpbasicService.GetOrgForHRModelCompletedEventArgs e)
        {
            OrgList = e.Result;
            forumList.Clear();
            foreach (EmpbasicService.OrgForHRModel i in e.Result)
            {
                forumList.Add(i);
            }
            AddTreeNode("全部单位", null);
        }

        private void AddTreeNode(string type, TreeViewItem treeViewItem)
        {
            List<EmpbasicService.OrgForHRModel> result = (from forumInfo in forumList
                                                          where forumInfo.Type == type
                                                          select forumInfo).ToList<EmpbasicService.OrgForHRModel>();

            if (result.Count > 0)
            {
                foreach (EmpbasicService.OrgForHRModel foruminfo in result)
                {
                    TreeViewItem objTreeNode = new TreeViewItem();

                    //StackPanel sp = new StackPanel();
                    CheckBox cb = new CheckBox();
                    cb.Content = foruminfo.Name;
                    cb.Tag = objTreeNode;
                    cb.DataContext = foruminfo;
                    //sp.Children.Add(cb);
                    cb.Click += new RoutedEventHandler(cb_Checked);
                    objTreeNode.Header = cb;
                    //objTreeNode.Header = foruminfo.Name;
                    //objTreeNode.DataContext = foruminfo;
                    //objTreeNode.Tag = foruminfo.ID;
                    if ((objTreeNode.Header as CheckBox).Content.ToString() == "组织机构") objTreeNode.IsExpanded = true;

                    //此样式将会添加的所有叶子结点上
                    //objTreeNode.ItemContainerStyle = this.Resources["RedItemStyle"] as Style;

                    //添加根节点
                    if (treeViewItem == null)
                    {
                        TreeOfLife.Items.Add(objTreeNode);
                    }
                    else
                    {
                        treeViewItem.Items.Add(objTreeNode);
                    }
                    AddTreeNode(foruminfo.Name, objTreeNode);
                }
            }
        }
        public int orgid { get; set; }
        public List<string> orgids = new List<string>();
        public string type { get; set; }
        void cb_Checked(object sender, RoutedEventArgs e)
        {
            CheckBox cb = sender as CheckBox;
            EmpbasicService.OrgForHRModel rm = cb.DataContext as EmpbasicService.OrgForHRModel;
            if (cb.IsChecked == true)
            {
                //if (orgids != null)
                //{
                //orgid = Convert.ToInt32(((EmpbasicService.OrgForHRModel)cb.DataContext).ID);
                //tbTitle.Text = cb.Content.ToString();
                if (!orgids.Contains(((EmpbasicService.OrgForHRModel)cb.DataContext).ID.ToString()))
                    orgids.Add(((EmpbasicService.OrgForHRModel)cb.DataContext).ID.ToString());
                string ss = "";
                foreach (string i in orgids)
                    ss += i + ",";
                if (string.IsNullOrEmpty(ss) || orgids.Contains("79")) ss = "0";
                else ss = ss.Substring(0, ss.Length - 1);
                LoadData(ss);
                CheckChildItem(cb.Tag as TreeViewItem);
            }
            else
            {
                //if (orgids != null)
                //{
                if (orgids != null)
                {
                    if (orgids.Contains(((EmpbasicService.OrgForHRModel)cb.DataContext).ID.ToString()))
                        orgids.Remove(((EmpbasicService.OrgForHRModel)cb.DataContext).ID.ToString());
                }
                string ss = "";
                foreach (string i in orgids)
                    ss += i + ",";
                if (ss.Length > 1) ss = ss.Substring(0, ss.Length - 1); else ss = "0";
                LoadData(ss);
                UnCheckChildItem(cb.Tag as TreeViewItem);
            }
        }

        void CheckChildItem(TreeViewItem item)
        {
            foreach (TreeViewItem tvi in item.Items)
            {
                if (tvi != null)
                {
                    CheckBox cb = tvi.Header as CheckBox;
                    cb.IsChecked = true;
                    if (!orgids.Contains(((EmpbasicService.OrgForHRModel)cb.DataContext).ID.ToString()))
                        orgids.Add(((EmpbasicService.OrgForHRModel)cb.DataContext).ID.ToString());
                    CheckChildItem(tvi);
                }
            }
        }
        void UnCheckChildItem(TreeViewItem item)
        {
            foreach (TreeViewItem tvi in item.Items)
            {
                if (tvi != null)
                {
                    CheckBox cb = tvi.Header as CheckBox;
                    cb.IsChecked = false;
                    if (orgids.Contains(((EmpbasicService.OrgForHRModel)cb.DataContext).ID.ToString()))
                        orgids.Remove(((EmpbasicService.OrgForHRModel)cb.DataContext).ID.ToString());
                    UnCheckChildItem(tvi);
                }
            }
        }
        #endregion
        #region 左右拖动的条
        private GridLength _lastColLeftLength;
        private GridLength _lastColRightLength;
        private void GridSpliteTo_ToLeft(object sender, EventArgs e)
        {
            //已经到最左边，直接返回
            if (colLeft.Width.Value == 0.0)
            {
                return;
            }

            //
            if (colRight.Width.Value == 0)
            {
                colLeft.Width = _lastColLeftLength;
                colRight.Width = _lastColRightLength;
            }
            else
            {
                _lastColLeftLength = colLeft.Width;
                _lastColRightLength = colRight.Width;

                colLeft.Width = new GridLength(0);
                colRight.Width = new GridLength(150, GridUnitType.Star);
            }
        }

        private void GridSpliteTo_ToRight(object sender, EventArgs e)
        {
            if (colRight.Width.Value == 0)
            {
                return;
            }

            if (colLeft.Width.Value == 0)
            {
                colLeft.Width = _lastColLeftLength;
                colRight.Width = _lastColRightLength;
            }
            else
            {
                _lastColLeftLength = colLeft.Width;
                _lastColRightLength = colRight.Width;

                colRight.Width = new GridLength(0);
                colLeft.Width = new GridLength(300, GridUnitType.Star);
            }
        }
        #endregion

        private void ListBox_SelectionChanged(object sender, SelectionChangedEventArgs e)
        {
            orgid = Convert.ToInt32(((OrgForHRModel)(ListBoxOfLife.SelectedItem)).ID);
            orgids.Clear();
            orgids.Add(orgid.ToString());
            LoadData(orgids[0]);
        }

        void Client_GetOrgForHRModelbyIDsCompleted(object sender, EmpbasicService.GetOrgForHRModelbyIDsCompletedEventArgs e)
        {
            ListBoxOfLife.ItemsSource = e.Result;
            ListBoxOfLife.SelectedIndex = 0;
            orgid = Convert.ToInt32(e.Result[0].ID);
            orgids.Clear();
            orgids.Add(orgid.ToString());
            LoadData(orgids[0]);
        }

        private string juese = "";
        void Client_GetDengLuJueSeCompleted(object sender, EmpbasicService.GetDengLuJueSeCompletedEventArgs e)
        {
            if (e.Result != "人事干部")
            {
                juese = "管理员";
                if (TreeOfLife.ItemsSource != null) TreeOfLife.ItemsSource = null;
                TreeOfLife.Visibility = System.Windows.Visibility.Visible;
                ListBoxOfLife.Visibility = System.Windows.Visibility.Collapsed;
                Client.GetOrgForHRModelAsync(0);
                //DGRole_admin.Visibility = System.Windows.Visibility.Visible;
                LoadData("0");
            }
            else
            {
                juese = "人事干部";
                TreeOfLife.Visibility = System.Windows.Visibility.Collapsed;
                ListBoxOfLife.Visibility = System.Windows.Visibility.Visible;
                Client.GetDengLuOrgAsync(Session.LoginUser.LoginName);
                //DGRole_admin.Visibility = System.Windows.Visibility.Collapsed;
            }
        }
        public String[] Oldorgids;
        void Client_GetDengLuOrgCompleted(object sender, EmpbasicService.GetDengLuOrgCompletedEventArgs e)
        {
            if (!string.IsNullOrEmpty(e.Result))
            {
                Oldorgids = e.Result.Split(',');
            }
            Client.GetOrgForHRModelbyIDsAsync("(" + e.Result + ")");
        }

        public void LoadData(string orgids)
        {
            client1.PeiXunEmpAsync(0, orgids);
            client1.GetPeiXunModelAsync(0);
        }

        void client1_PeiXunEmpCompleted(object sender, PeiXunService.PeiXunEmpCompletedEventArgs e)
        {
            DGRole_admin.ItemsSource = null;
            DGRole_admin.ItemsSource = e.Result;
        }
        void client1_GetPeiXunModelCompleted(object sender, PeiXunService.GetPeiXunModelCompletedEventArgs e)
        {
            DGRole.ItemsSource = null;
            DGRole.ItemsSource = e.Result;
        }
        private void NewData_Click_admin(object sender, RoutedEventArgs e)
        {
            if(orgids.Count != 1)
            {
                SilverlightMessageBoxLibrary.Message.ErrorMessage("请选择一个单位进行人员上报！");
                return;
            }
            
            var seljw = this.DGRole.SelectedItem as PeiXunService.PeiXunModel;
            if (seljw != null)
            {
                client1.ShiFouChaoGuoPiaoShuAsync(seljw.ID, Convert.ToInt32(orgids[0]));

            }
            else SilverlightMessageBoxLibrary.Message.ErrorMessage("请选择培训信息！");
        }

        void client1_ShiFouChaoGuoPiaoShuCompleted(object sender, PeiXunService.ShiFouChaoGuoPiaoShuCompletedEventArgs e)
        {
            if(e.Result > 0)
            {
                string or = "";
                if (orgids.Count > 0)
                {
                    foreach (string i in orgids)
                    {
                        or += i + ",";
                    }
                    or = or.Substring(0, or.Length - 1);
                }
                var seljw = this.DGRole.SelectedItem as PeiXunService.PeiXunModel;
                if (seljw != null)
                {
                    AddPeiXunEmpWindow RMWindow = new AddPeiXunEmpWindow(or, seljw.ID, e.Result);
                    RMWindow.Closed += new EventHandler(RMWindow_Closed);
                    RMWindow.Show();

                }
                
            }
            else
            {
                SilverlightMessageBoxLibrary.Message.ErrorMessage("该单位没有参加培训，不可上报参加培训人员！");
                return;
            }
        }

        void RMWindow_Closed(object sender, EventArgs e)
        {
            string or = "";
            if (orgids.Count > 0)
            {
                foreach (string i in orgids)
                {
                    or += i + ",";
                }
                or = or.Substring(0, or.Length - 1);
            }
            else or = "0";
            LoadData(or);
        }
    }
}
